<template>
	<div class="chat" ref="myChat">
		<div v-for="(item,index) in messages" :key="index">
			<div v-if="item.role=='user'">
				<span style="color: red;">我的:</span>
				<em style="color: goldenrod;">{{item.content}}</em>
			</div>
			<div v-if="item.role=='assistant'">
				<div style="color:blue;text-align: right;">
					{{item.role}}:
				</div>
				<div v-html="item.content"></div>
			</div>
		</div>
	</div>
	<div class="hint">
		<input placeholder="请输入你聊天信息" type="text" v-model="msg" />
		<button @click="myChat">Send</button>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				msg: "请列出和人工智能相关的5篇论文题目", //方便测试
				messages:[]
			}
		},
		mounted() {
			//有三个角色system,user,assistant
			this.messages.push({
				role:"system",
				content:"You are a warm-hearted assistant,and you only speak Chinese"
			})
			this.scrollToBtm();
		},
		methods: {
			scrollToBtm(){
				this.$nextTick(()=>{
					let elm=this.$refs.myChat;
					elm.scrollTop=elm.scrollHeight;
				})
			},
			async myChat() {
				this.messages.push({
					role: 'user',
					content: this.msg
				})
				this.messages.push({
					role: 'assistant',
					content: ""
				})	
				let msgLen=this.messages.length;
					
				let url = "http://localhost:1234/v1/chat/completions"
				//流式响应，axios在nodejs中支持，浏览器不支持，我们使用fetch
				let response = await fetch(url, {
					method: "post",
					headers: {
						"content-type": "application/json"
					},
					body: JSON.stringify({
						"model": "qwen2.5-7b-instruct-1m",
						"stream": true,				
						//这部分可以放历史记录，思考完成。
						"messages": this.messages,
						"temperature": 0.7
					})
				});
				
				let reader = response.body.getReader();
				
				//利用reader读取每块，并解析
				let decoder = new TextDecoder();
				
				//循环解析直到结果结束
				while (true) {
					let { value, done } = await reader.read(); //读取并解析每块
					if (done) break; //结束标志
					const chunk = decoder.decode(value); //数据块，可能包含多个
					
					//数据是以data: 开头，过滤头，转换为json格式
					let jsonStr=chunk.slice(6);
					try{
						let jsonData=JSON.parse(jsonStr);
						//console.log(jsonData);
						let str=jsonData.choices[0].delta.content;
						this.messages[msgLen-1].content+=str.replace(/[\n]+/g, "<br>");
					}catch(err){
						
					}
				}
					
			}
		},
	}
</script>

<style scoped>
	.chat{
		height: 480px;
		width: 90%;
		overflow-y: hidden;
		border: 1px solid gray;
	}
	.hint{
		margin-top: 5px;
		display: flex;
		flex-direction: row;
	}
	input{
		width: 70%;
		border: solid 1px darkgray;
		font-size: 18px;
		line-height: 24px;
	}
</style>